﻿#include "dul_linked_list.h"

DuLinkList InitLinkedList() {

    DuLinkList head = (DuLinkList)malloc(sizeof(DulNode));
    if (!head) exit(1);
    head->prev = head;
    head->next = head;
    return head;
}

void ListInsert(DuLinkList head, int i, ElemType e) {

    DulNode* p = head;
    int j = 0;
    
    while (p->next != head && j < i - 1) {
        p = p->next;
        j++;
    }

    if (j != i - 1) return;

    DulNode* s = (DulNode*)malloc(sizeof(DulNode));
    if (!s) exit(1);
    
    s->data = e;
    s->next = p->next;
    p->next->prev = s;
    p->next = s;
    s->prev = p;

    return;
}

void ListDelete(DuLinkList head, int i) {

    DulNode* p = head->next;
    int j = 1;

    while (p != head && j < i) {
        p = p->next;
        j++;
    }
    if (p == head || j != i) return;

    p->prev->next = p->next;
    p->next->prev = p->prev;
    
    free(p);
}

int GetElem(DuLinkList head, ElemType e) {

    DulNode* p = head->next;

    int position = 1;

    while (p != head) {

        if (p->data == e) return position;

        p = p->next;

        position++;
    }
    return -1;
}

int GetElemType(DuLinkList head, int i) {

    DulNode* p = head->next;

    int j = 1;

    while (p != head && j < i) {
        p = p->next;
        j++;
    }

    if (p == head || j != i) {
        printf("\nPosition %d is invalid.\n", i);
        return -1;
    }
    return p->data;
}

int ListLength(DuLinkList head) {

    DulNode* p = head->next;
    int length = 0;

    while (p != head) {
        length++;
        p = p->next;
    }

    return length;
}

void Print(DuLinkList head) {

    DulNode* p = head->next;

    while (p != head) {
        printf("%d ", p->data);
        p = p->next;
    }

    printf("\n");
}

void ListClear(DuLinkList head) {

    DulNode* p = head->next;
    
    while (p != head) {
        DulNode* q = p->next;
        free(p);
        p = q;
    }
    head->next = head;
    head->prev = head;
}



